<?php
/**
 * +--------------------------------------------------------------
 * | eLuoPHP
 * +--------------------------------------------------------------
 * | Copyright (c) 2016-2018 http://qxwoo.cn All rights reserved.
 * +--------------------------------------------------------------
 * | y139w [y139w@163.com]
 * +--------------------------------------------------------------
 * | 路由处理类文件
 * +--------------------------------------------------------------
 */

namespace luo;


class Router
{

    /**
     * 存放当前类的一个对象
     * @var null
     */
    private static $_instance = null;
    private static $route = [];

    private $param = [];

    /**
     * 静态方法获取当前类的实例
     * @return Router
     */
    public static function instance(){

        // 只实例化一次当前类
        if( !(self::$_instance instanceof self) ){
            self::$_instance = ( new self() );
        }
        // 实例化当前类，返回一个当前类的对象
        return self::$_instance;

    }

    /**
     * 验证路由
     * @param $path
     * @return array|bool
     */
    public function check($path){

        $result = false;
        $template = Config::get('template');
        if($path && strpos($path, $template['template_ext'])){
            $path = str_replace($template['template_ext'], '', $path);
        }
        $router = $this->parseUrl($path);
        $mca = implode('/', $router);
        if(array_key_exists(trim($mca, '/'), self::$route)){
            $result = explode('/', self::$route[trim($mca, '/')]);
            // 获取模块
            $module = array_shift($result) ? : null;
            // 获取控制器
            $controller = array_shift($result) ? : null;
            // 获取方法
            $action = array_shift($result) ? : null;
            // 组装路由
            $result = [$module, $controller, $action];
        }

        return $result;

    }

    /**
     * 注册路由
     * @param array $route
     * @return $this
     */
    public function register($route = []){

        foreach ($route as $k => $v){
            self::$route[$k] = $v;
        }
        return $this;

    }

    /**
     * @param string $mca
     * @return array|string|null
     */
    public function get($mca = ''){

        $flipRoute = array_flip(self::$route);
        if(!empty($mca)){
            return empty($flipRoute[$mca]) ? $mca : $flipRoute[$mca];
        }
        return $flipRoute;

    }

    /**
     * 获取配置项
     * @param null $name
     * @return array|mixed|null
     */
    public static function getCon($name = null){

        if(empty($name)){
            // 如果为空，就返回配置
            return self::$route;
        }else if(is_string($name)){
            // 获取配置项
            return self::$route[$name];
        }
        return null;

    }

    /**
     * 设置配置项
     * @param $name
     * @param null $value
     * @return mixed
     */
    public static function set($name, $value = null){

        if(is_string($name)){
            // 如果是字符串
            self::$route[$name] = $value;
        }else if(is_array($name)){
            // 如果是数组
            foreach($name as $key=>$val){
                self::$route[$key] = $val;
            }
        }
        return self::$route;

    }

    /**
     * 加载配置文件
     * @param $file
     * @return mixed
     */
    public static function load($file, $RouteType = false){

        if(is_file($file)){
            // 获取文件扩展名
            $type = pathinfo($file, PATHINFO_EXTENSION);
            $router = '';
            // 当扩展名为php时
            if('php' == $type){
                $router = include $file;
            }
            if($RouteType){
                $router = [$RouteType => include $file];
            }
            self::set($router);
        }
        return ;

    }

    /**
     * 解析URL
     * @param $url
     * @return array
     */
    public function parseUrl($url){

        $urlArray = $this->parseUrlPath($url);
        $router = [null, null, null];
        // 获取当前路由地址
        $path = $urlArray['path'];
        if (!empty($path)){
            // 获取模块
            $module = array_shift($path) ? : null;
            // 获取控制器
            $controller = array_shift($path) ? : null;
            // 获取方法
            $action = array_shift($path) ? : null;
            $template = Config::get('template');
            if($action && strpos($action, $template['template_ext'])){
                $action = str_replace($template['template_ext'], '', $action);
            }
            // 组装路由
            $router = [$module, $controller, $action];
        }
        $vars = [];
        for ($i=0; $i<count($path); $i = $i+2) {
            if(!empty($path[$i])){
                $vars[$path[$i]] = empty($path[$i + 1]) ? '' : $path[$i + 1];
            }
        }
        $_GET = array_merge($_GET, $urlArray['var'], $vars);
        return $router;

    }

    /**
     * 处理URL路径
     * @param $url
     * @return array
     */
    private function parseUrlPath($url){

        $url = trim($url, '/');
        $var = [];
        $path = [];
        if (false !== strpos($url, '?')) {
            // [模块/控制器/操作?]参数1=值1&参数2=值2...
            $info = parse_url($url);
            $path = explode('/', $info['path']);
            parse_str($info['query'], $var);
        } elseif (strpos($url, '/')) {
            // [模块/控制器/操作]
            $path = explode('/', $url);
        } elseif (false !== strpos($url, '=')) {
            // 参数1=值1&参数2=值2...
            parse_str($url, $var);
        } else {
            $path = [$url];
        }
        return ['path' => $path, 'var' => $var];

    }

}